import axios from 'axios'
import { VueAxios } from './axios'
import storage from 'store'
import notification from 'ant-design-vue/es/notification'

// 创建 axios 实例
const request = axios.create({
  // API 请求的默认前缀
  baseURL: process.env.VUE_APP_API_BASE_URL
})

// 异常拦截处理器
const errorHandler = (error) => {
  if (error.response) {
    // 登录失效
    if (error.response.status === 401) {
      storage.remove('token')
      notification.error({ message: '错误', description: "登录过期，请重新登录", duration: 3 })
      setTimeout(() => {
        window.location.reload()
      }, 1500)
    }

    // 业务异常
    if (error.response.status === 201) {
      notification.error({ message: '错误', description: error.response.data.errors, duration: 3 })
    }
  }
  return Promise.reject(error)
}

// request interceptor
request.interceptors.request.use(config => {
  const token = storage.get('token')
  // // 如果 token 存在
  // // 让每个请求携带自定义 token 请根据实际情况自行修改
  if (token) {
    config.headers['Authorization'] = `Bearer ${token}`
  }
  return config
}, errorHandler)

// response interceptor
request.interceptors.response.use((response) => {
  return response.data
}, errorHandler)

const installer = {
  vm: {},
  install (Vue) {
    Vue.use(VueAxios, request)
  }
}

export default request

export {
  installer as VueAxios,
  request as axios
}
